<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Models\V1\Department;
use App\Models\V1\Faculty;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\V1\DepartmentRequest;
use Log;

class DepartmentsController extends Controller
{
    /**
     * 显示部门数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.departments');
    }

    /**
     * 获取部门数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的部门数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');
        //新添加
        $field = $request->get('field');
        $order = $request->get('order');

        // 获取符合查询条件的部门数据
        $data = $this->getDepartmentList($currentPage, $rows, $keywords, $field, $order);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['show_level'] = '' . $item['show_level'];
                    $formatItem['parent_code'] = $this->getDepartmentNameByCode($item['parent_code']);
                    $formatItem['telephone'] = $item['telephone'];
                    $formatItem['principal'] = $item['principal'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }

                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     * 进入单条部门数据显示界面（适用于编辑setParent、查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        $data['code'] = $request->input('code');
        $currentDepartment = $this->getDepartmentByCode($data['code']);
        if ($data['view'] === 'viewData') {
            $currentDepartment['parent_code'] = $this->getDepartmentNameByCode($currentDepartment['parent_code']);
        }
        $data['itemData'] = $currentDepartment;
        $data['parentList'] = $this->getParentDepartmentList()->toArray();
        return view('v1.form.department_item', $data);
    }

    /**
     * 进入部门数据删除界面（适用于删除、批量删除）
     *
     * @param Request $request
     */
    public function operateView(Request $request)
    {
        $data['view'] = $request->input('view');

        if ($data['view'] === 'deleteBatchData') {
            // 解析code字符串成数组
            $codeList = explode(",", $request->input('code'));
            $data['code'] = $request->input('code');
            $operateList = array();
            foreach ($codeList as $code) {
                // 获取当前部门
                $currentDepartment = $this->getDepartmentByCode($code);
                if ($currentDepartment !== null) {
                    array_push($operateList, $currentDepartment->toArray());
                }
            }
            $data['itemCount'] = sizeof($operateList);
            $data['itemData'] = $operateList;
            $data['departmentList'] = $this->getAllDepartmentList()->toArray();
        } else {
            $data['code'] = $request->input('code');
            // 获取当前部门
            $currentDepartment = $this->getDepartmentByCode($data['code']);

            $data['itemData'] = $currentDepartment;
            $data['departmentList'] = $this->getAllDepartmentList()->toArray();
        }

        return view('v1.form.department_operate', $data);
    }

    /**
     * 显示部门数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser['code'];

        return view('v1.form.upload_excel',$data);
    }

    /**
     * 更新部门基本信息(单元格)
     *
     * @param DepartmentRequest $request
     * @return array
     */
    public function updateCellData(DepartmentRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '部门代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateDepartment($request);

            // 更新部门信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '部门代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 更新部门基本信息
     *
     * @param DepartmentRequest $request
     * @return array
     */
    public function updateData(DepartmentRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '部门代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateDepartment($request);

            // 更新部门信息
            $successFlag = $this->handleUpdate($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '部门代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }

    /**
     * 删除部门基本信息
     *
     * @param DepartmentRequest $request
     * @return array
     */
    public function deleteData(DepartmentRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '部门代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateDepartment($request);

            // 删除部门信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '部门代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除部门基本信息
     *
     * @param DepartmentRequest $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '部门批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['captcha'] = 'bail|required|captcha';
            $messages['captcha.required'] = '验证码不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request,$rules,$messages);
            // 删除部门信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '部门批量删除成功！';
            }
        }

        return $response;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的部门列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getDepartmentList($page = 1, $rows, $keywords, $field, $order)
    {
        if (!isset($field) || empty($field) || !isset($order) || empty($order)) {
            //不存在根据指定字段排序
            if (!isset($keywords) || empty($keywords)) {
                $data = Department::orderBy('show_level', 'asc')->paginate($rows, ['*'], 'page', $page);
            } else {
                $data = Department::where('name', 'like', '%' . $keywords . '%')->orderBy('show_level', 'asc')
                    ->paginate($rows, ['*'], 'page', $page);
            }
        }else {
            if (!isset($keywords) || empty($keywords)) {
                $data = Department::orderBy($field, $order)->paginate($rows, ['*'], 'page', $page);
            } else {
                $data = Department::where('name', 'like', '%' . $keywords . '%')->orderBy($field, $order)
                    ->paginate($rows, ['*'], 'page', $page);
            }
        }
        return $data;
    }

    /**
     * 获取所有一级部门列表
     *
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    private function getParentDepartmentList()
    {
        $data = Department::where('parent_code', '=', '0')->orderBy('show_level', 'asc')->get(['code', 'name']);
        return $data;
    }

    /**
     * 获取所有部门列表
     *
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    private function getAllDepartmentList()
    {
        $data = Department::orderBy('show_level', 'asc')->get(['code', 'name']);
        return $data;
    }

    /**
     * 根据部门代码获取对应部门名称
     *
     * @param $code
     * @return mixed|string
     */
    private function getDepartmentNameByCode($code)
    {
        $departName = '无';

        if ($code !== '0') {
            $parentDepartment = $this->getDepartmentByCode($code);
            $departName = $parentDepartment['name'];
        }

        return $departName;
    }

    /**
     * 根据部门代码获取对应部门信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getDepartmentByCode($code)
    {
        $department = Department::where('code', $code)->first();
        return $department;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理部门信息验证请求
     *
     * @param Request $request
     */
    private function validateDepartment(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑处理功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新部门信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            // 解析code字符串成数组
            $codeList = explode(",", $request->input('code'));

            foreach ($codeList as $code) {

                $ncode = $request->input('nc' . $code);

                // 更新所属部门是待删除部门的部门数据
                $updateDepart = [
                    'parent_code' => $ncode,
                ];
                Department::where('code', $code)->update($updateDepart);

                // 更新所属部门是待删除部门的员工数据
                $updateFaculty = [
                    'department_code' => $ncode,
                ];
                Faculty::where('department_code', $code)->update($updateFaculty);

                $rspObj = Department::where('code', $code)->delete();
            }
        } else { // 单条删除
            // 更新所属部门是待删除部门的部门数据
            $updateDepart = [
                'parent_code' => $request->input('newcode'),
            ];
            Department::where('code', $where)->update($updateDepart);

            // 更新所属部门是待删除部门的员工数据
            $updateFaculty = [
                'department_code' => $request->input('newcode'),
            ];
            Faculty::where('department_code', $where)->update($updateFaculty);

            $rspObj = Department::where('code', $where)
                ->delete();
        }

        return $rspObj;
    }

    /**
     * 处理更新部门信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'name' => $request->input('name'),
                'parent_code' => $request->input('parent_code'),
                'telephone' => $request->input('telephone'),
                'principal' => $request->input('principal'),
                'show_level' => $request->input('show_level') ? $request->input('show_level') : 0,
            ];
        }

        $rspObj = Department::where('code', $where)
            ->update($updateData);

        return $rspObj;
    }
}
